<?php

/**
 * Accountresumes Controller
 *
 * PHP version 5
 *
 * @category Controller
 * @package  Croogo
 * @version  1.0
 * @author   Tran Van Dung <dungtv@ic-t.info>
 * @license  http://www.opensource.org/licenses/mit-license.php The MIT License
 * @link     http://www.croogo.org
 */
class AccountresumesController extends AppController {

    /**
     * Controller name
     *
     * @var string
     * @access public
     */
    public $name = 'Accountresumes';
    /**
     * Models used by the Controller
     *
     * @var array
     * @access public
     */
    public $uses = array('Accountresume', 'Insurancetype', 'Aihcontact', 'Market', 'Bank', 'Currency', 'Paymentschedule', 'Placementdetailt', 'Reminder');
    /**
     * Helpers used by the Controller
     *
     * @var array
     * @access public
     */
    public $helpers = array('Text', 'Html', 'Js');
    protected $paginate = array(
        'limit' => 10,
    );

    /**
     * Before executing controller actions
     *
     * @return void
     * @access public
     */
    public function beforeFilter() {
        parent::beforeFilter();

        if ($this->action == 'add' || $this->action == 'edit' || $this->action == 'admin_add' || $this->action == 'admin_edit') {
            $this->Security->validatePost = false;
        }
//        $this->Accountresume->unbindModel(array('hasAndBelongsToMany' => array('Bank')));
    }

    /**
     * Admin index
     *
     * @return void
     * @access public
     */
    public function admin_index() {
        $this->set('title_for_layout', __('ACCOUNT RESUME LIST'));

        $scriptSearchBox = $this->scriptSearchBox();
        $this->set('scriptSearchBox', $scriptSearchBox);

        $this->Session->delete('PlacementDetail');
        $this->Session->delete('PaymentSchedule');
        $this->Session->delete('Market');
        $this->Session->delete('UnderWriter');
        $this->Session->delete('cur_producing_brokers');
        $this->Session->delete('cur_markets');
        $this->Session->delete('cur_currency');

        $this->Accountresume->recursive = 0;
        $this->paginate['Accountresume']['order'] = 'Accountresume.date DESC';
        $this->set('accountresumes', $this->paginate());
    }

    public function admin_search() {
        $this->set('title_for_layout', __('ACCOUNT RESUME SEARCH'));

        $scriptSearchBox = $this->scriptSearchBox();
        $this->set('scriptSearchBox', $scriptSearchBox);
        $q = $this->params['named']['q'];
        $this->set('q', $q);

        $this->Paymentschedule->recursive = 0;
        $refids = $this->Paymentschedule->find('list', array(
            'conditions' => array('OR' => array(
                        'Paymentschedule.payer_name LIKE' => '%' . $q . '%',
                        'Paymentschedule.markets LIKE' => '%' . $q . '%',
                    )
                ),
            'fields' => array('accountresume_id'),
        ));
        
        $this->Accountresume->recursive = 0;
        $this->paginate['Accountresume']['conditions'] = array('OR' => array(
                        'Accountresume.refid' => $refids,
                        'Accountresume.reinsured LIKE' => '%' . $q . '%',
                        'Accountresume.original_insured LIKE' => '%' . $q . '%',
                    )
                );
        $this->paginate['Accountresume']['order'] = 'Accountresume.date ASC';

        $this->set('accountresumes', $this->paginate());
    }

    public function windowMsg() {
        $output = "
                $(function(){
                    // don't forget this init!      
                    $.initWindowMsg();

                    var childWin;
                    $('.openWin').click(function(){
                        var contacttype = $(this).attr('rel');
                        if(contacttype < 1 && contacttype > 5){
                            contacttype = 1;
                        }
                        contacttype = '/contacttype:'+contacttype;
                        childWin = window.open('" . Router::url('/admin/aihcontacts/add/rel:browse', true) . "'+contacttype, 'child', 'modal,width=1024,height=768,scrollbars=yes');
                        if (window.focus) {childWin.focus()}
                    });
                    
                    $('.openWinMarket').click(function(){
                        childWin = window.open('" . Router::url('/admin/markets/add/rel:browse', true) . "', 'child', 'modal,width=1024,height=768,scrollbars=yes');
                        if (window.focus) {childWin.focus()}
                    });

                    // set up the message handlers, listen for events 'childMsg1' and 'childMsg2'     
                    $.windowMsg('childMsg1', function(message) {
                        var temp = message.split(':::');
                        //
                    });

                    $.windowMsg('childMsg2', function(message) {
                        var temp = message.split(':::');
                        //
                    });
                    
                    $.windowMsg('childMsg', function(message) {
                        var temp = message.split(':::');
                        switch(temp[2]*1){
                            case 1:
                                $('select#ReinsurerReinsurer').append('<option value=\"'+temp[0]+'\">'+temp[1]+'</option>');
                                break;
                            case 2:
                                $('select#ProducingbrokerProducingbroker').append('<option value=\"'+temp[0]+'\">'+temp[1]+'</option>');
                                break;
                            case 3:
                                $('select#OriginalinsurerOriginalinsurer').append('<option value=\"'+temp[0]+'\">'+temp[1]+'</option>');
                                break;
                            case 4:
                                //
                                break;
                            default:
                                break;
                        }
                    });
                    
                    $.windowMsg('childMsgMarket', function(message) {
                        var temp = message.split(':::');
                        $('select#MarketMarket').append('<option value=\"'+temp[0]+'\">'+temp[1]+'</option>');
                    });
                });";

        return $output;
    }
    
    public function reportScript() {
        $output = "
                $(function(){
                    var childWin;
                    $('a.cover_note').click(function() {
                        var id = $('#AccountresumeId').val();
                        if(id!='') {
                            childWin = window.open('".Router::url('/admin/accountresumes/upload_cover_note/', true)."'+id, 'child', 'modal,width=1024,height=768,scrollbars=yes');
                        }else{
                            alert('Not exist account resume!')
                        }
                    });
                    $('a.debit_note').click(function() {
                        var id = $('#AccountresumeId').val();
                        if(id!='') {
                            childWin = window.open('".Router::url('/admin/accountresumes/debit_note/', true)."'+id, 'child', 'modal,width=1024,height=768,scrollbars=yes');
                        }else{
                            alert('Not exist account resume!')
                        }
                    });
                    $('a.premium_closing').click(function() {
                        var id = $('#AccountresumeId').val();
                        if(id!='') {
                            var i = 1;
                            var child;
                            $('input[name=\"Markets[]\"]').each(function(){
                                if($(this).val()*1>0) {
                                    child = 'child'+i;
                                    childWin = window.open('".Router::url('/admin/accountresumes/premium_closing/', true)."'+id+'/'+$(this).val(), child, 'modal,width=1024,height=768,scrollbars=yes');
                                    i++;
                                }
                            });
                        }else{
                            alert('Not exist account resume!')
                        }
                    });
                    $('a.download_pdf').click(function() {
                        var id = $('#AccountresumeId').val();
                        if(id!='') {
                            childWin = window.open('".Router::url('/admin/accountresumes/pdf_review/', true)."'+id, 'child', 'modal,width=1024,height=768,scrollbars=yes');
                        }else{
                            alert('Not exist account resume!')
                        }
                    });
                });";

        return $output;
    }

    /**
     * Admin add
     *
     * @return void
     * @access public
     */
    public function admin_add() {
        $this->set('title_for_layout', __('ACCOUNT RESUME DETAIL'));

        $scriptDate = $this->datePicker();
        $this->set('scriptDate', $scriptDate);

        $redirect = array('action' => 'index');

        if (!empty($this->request->data)) {
            $accountresume = $this->data['Accountresume'];
            $accountresume['date'] = $this->formatDate($accountresume['date']);
            $order_premium = $accountresume['order_premium']; 
            $accountresume['insurancetype_id'] = $this->data['Insurancetype']['Insurancetype'];
            $accountresume['currency_id'] = $this->data['Currency']['Currency'];
            // new placement detailt
            $aih_total_amount = 0;
            foreach ($this->request->data['Placementdetailt'] as $placementdetailt) {
                $aih_total_amount += $order_premium * $placementdetailt['contact_rate'] /100 * $placementdetailt['aih_rate'] /100;
            }
            $aih_total_amount = str_replace(',', '', number_format($aih_total_amount, 2));
            
            $placementdetailts = array('Placementdetailt' => array());
            $sub_order_hereon = array();
            $brokerage_rate = array();
            foreach ($this->request->data['Placementdetailt'] as $placementdetailt) {
                $sub_order_hereon[$placementdetailt['contact_id']] = $placementdetailt['contact_rate'];
                $brokerage_rate[$placementdetailt['contact_id']] = $placementdetailt['brokerage_rate'];
                $placementdetailt['accountresume_id'] = $accountresume['refid'];
                $placementdetailt['refid_edit'] = $accountresume['refid_edit'];
                $temp_contact_amount = $order_premium * $placementdetailt['contact_rate'] /100 * (100 - $placementdetailt['aih_rate']) /100;
                $placementdetailt['contact_amount'] = str_replace(',', '', number_format($temp_contact_amount, 2));
                $placementdetailt['aih_total_amount'] = $aih_total_amount;
                $placementdetailt['currency_id'] = $this->data['Currency']['Currency'];
                $placementdetailt['currency'] = $accountresume['currency'];
                $placementdetailts['Placementdetailt'][] = $placementdetailt;
            }
            
            // save placement detailt
            $count = count($placementdetailts['Placementdetailt']);
            $this->Placementdetailt->saveAll($placementdetailts['Placementdetailt']);
            $lastInsertId = $this->Placementdetailt->getLastInsertId();
            $lastInsertIds = $this->Placementdetailt->find('list', array('order' => array('id desc'), 'limit' => $count, 'conditions' => array('id <=' => $lastInsertId), 'fields' => array('id')));
            $accountresume['placementdetailts'] = $this->Accountresume->encodeData($lastInsertIds);

            $count = count($this->request->data['Paymentschedule']);
            $paymentschedules['Paymentschedule'] = array();
            $reminders = array();
            $i = 0;
            foreach ($this->request->data['Paymentschedule'] as $paymentschedule) {
                $reminders[$i]['summary'] = $accountresume['refid_edit'] . ' - '.$paymentschedule['payer_name'].' pay to AIH';
//                $reminders[$i]['summary'] = 'Reference #: ' . $accountresume['refid_edit'] . ' - Payment Schedule from '.$paymentschedule['payer_name'].' to '.  implode(', ', $paymentschedule['rel_market_name']);
                $reminders[$i]['description'] = $reminders[$i]['summary'];
                $reminders[$i]['dtstart'] = $this->formatDate($paymentschedule['broker_date']);
                $i++;
                // 
                $markets = array();
                foreach ($paymentschedule['rel_market_id'] as $market_id) {
                    $markets[$market_id] = array(
                        $paymentschedule['rel_market_name'][$market_id],
                        $paymentschedule['rel_market_under_writer'][$market_id],
                        $paymentschedule['rel_market_date'][$market_id],
                        $paymentschedule['rel_market_amount'][$market_id],
                        $sub_order_hereon[$market_id],
                        $brokerage_rate[$market_id],);
                }
                $paymentschedule['markets'] = $this->Accountresume->encodeData($markets, array('json' => true, 'trim' => false));
                
                $paymentschedule['accountresume_id'] = $accountresume['refid'];
                $paymentschedule['refid_edit'] = $accountresume['refid_edit'];
                $paymentschedule['due_date'] = $accountresume['date'];
                $paymentschedule['broker_date'] = $this->formatDate($paymentschedule['broker_date']);
                $paymentschedule['aih_date'] = $this->formatDate($paymentschedule['aih_date']);
                $paymentschedule['currency'] = $accountresume['currency'];
                $paymentschedule['currency_id'] = $this->data['Currency']['Currency'];
                $paymentschedules['Paymentschedule'][] = $paymentschedule;
//                }
            }
            // save payment schedule
            $this->Paymentschedule->saveAll($paymentschedules['Paymentschedule']);
            $lastInsertId = $this->Paymentschedule->getLastInsertId();
            $lastInsertIds = $this->Paymentschedule->find('list', array('order' => array('id desc'), 'limit' => $count, 'conditions' => array('id <=' => $lastInsertId), 'fields' => array('id')));
            $accountresume['paymentschedules'] = $this->Accountresume->encodeData($lastInsertIds);
            $i--;
            foreach ($lastInsertIds as $id) {
                $reminders[$i]['paymentschedule_id'] = $id;
                $i--;
            }
            foreach ($reminders as $reminder) {
                $this->Accountresume->reminder($reminder);
            }

            $accountresume['producing_brokers'] = $this->Accountresume->encodeData($this->data['Producingbrokers']);
            $this->Accountresume->lock($this->data['Producingbrokers'], 'cc_aihcontacts', 1);
            $accountresume['markets'] = $this->Accountresume->encodeData($this->data['Markets']);
            $this->Accountresume->lock($this->data['Markets'], 'cc_markets', 1);
            $this->Accountresume->lock(array($accountresume['insurancetype_id']), 'cc_insurancetypes', 1);
            $this->Accountresume->lock(array($accountresume['currency_id']), 'cc_currencies', 1);

            $accountresume['from_date'] = $this->formatDate($accountresume['from_date']);
            $accountresume['to_date'] = $this->formatDate($accountresume['to_date']);

            $this->Accountresume->create();
            if ($this->Accountresume->save($accountresume)) {

                //$this->Session->setFlash(__('The Account Resume has been saved'), 'default', array('class' => 'success'));

                $this->redirect($redirect);
            } else {
                $this->Session->setFlash(__('The Account Resume could not be saved. Please, try again.'), 'default', array('class' => 'error'));
            }
        }
        $scriptWindowMsg = $this->windowMsg();
        $this->set('scriptWindowMsg', $scriptWindowMsg);

        $producingbrokers = $this->Aihcontact->find('list', array('conditions' => array('Aihcontact.contacttype_id' => 5)));
        $this->set(compact('producingbrokers'));

        $markets = $this->Market->find('list', array('fields' => array('Market.id', 'Market.name'), 'order' => array('Market.name ASC')));
        $this->set(compact('markets'));

        $currencies = $this->Currency->find('list', array('fields' => array('Currency.id', 'Currency.name')));
        $this->set(compact('currencies'));

        $insurancetypes = $this->Accountresume->Insurancetype->find('list');
        $this->set(compact('insurancetypes'));
    }

    public function admin_add_paymentschedule($payer=0, $payer_name=null, $marketers=null) {
        $this->layout = 'ajax';
        $this->set('payer', $payer);
        $this->set('payer_name', $payer_name);
        
        $markets = $this->Market->find('all', array('conditions' => array('Market.id' => explode('-', $marketers)), 'order' => array('Market.name ASC')));
        $this->set('markets', $markets);
    }

    public function admin_add_placementdetail($id=null) {
        $this->layout = 'ajax';
        $market = $this->Market->find('first', array('conditions' => array('Market.id' => $id), 'order' => array('Market.name ASC')));
        $this->set('market', $market);
    }

    public function admin_delete_paymentschedule($ids=null) {
        $this->layout = 'ajax';
        $success = false;
        $temp = explode('-', $ids);
        foreach ($temp as $id) {
            $uid = String::uuid();
            $this->Session->write('PaymentSchedule.' . $uid . '.Id', $id);
        }
        if ($ids != '') {
            $success = true;
        }
        $success = $this->Accountresume->encodeData(array('success' => $success), array('json' => true, 'trim' => false));
        $this->set('success', $success);
    }

    public function admin_delete_placementdetail($id=null) {
        $this->layout = 'ajax';
        $success = false;
        $uid = String::uuid();
        $this->Session->write('PlacementDetail.' . $uid . '.Id', $id);
        if ($id != '') {
            $success = true;
        }
        $success = $this->Accountresume->encodeData(array('success' => $success), array('json' => true, 'trim' => false));
        $this->set('success', $success);
    }

    public function admin_delete_market($id=null) {
        $this->layout = 'ajax';
        $success = false;
        $uid = String::uuid();
        $this->Session->write('Market.' . $uid . '.Id', $id);
        if ($id != '') {
            $success = true;
        }
        $success = $this->Accountresume->encodeData(array('success' => $success), array('json' => true, 'trim' => false));
        $this->set('success', $success);
    }

    public function admin_delete_underwriter($id=null) {
        $this->layout = 'ajax';
        $success = false;
        $uid = String::uuid();
        $this->Session->write('UnderWriter.' . $uid . '.Id', $id);
        if ($id != '') {
            $success = true;
        }
        $success = $this->Accountresume->encodeData(array('success' => $success), array('json' => true, 'trim' => false));
        $this->set('success', $success);
    }

    public function admin_get_underwriter($id=null) {
        $this->layout = 'ajax';
        $success = false;
        if ($id != '') {
            $market = $this->Market->find('first', array('fields' => array('Market.id', 'Market.under_writer'), 'conditions' => array('Market.id' => $id), 'order' => array('Market.name ASC')));
            if ($market) {
                $success = true;
                $success = $this->Accountresume->encodeData(array('success' => $success, 'underwriter' => $market['Market']['under_writer']), array('json' => true, 'trim' => false));
            }
        } else {
            $success = $this->Accountresume->encodeData(array('success' => $success));
        }
        $this->set('success', $success);
    }

    public function admin_get_contacts($ids=null) {
        $this->layout = 'ajax';
        $success = false;
        if ($ids != '') {
            $contacts = $this->Aihcontact->find('list', array('fields' => array('Aihcontact.id', 'Aihcontact.name'), 'conditions' => array('Aihcontact.id' => explode('-', $ids))));
            if ($contacts) {
                $success = true;
                $success = $this->Accountresume->encodeData(array('success' => $success, 'contacts' => $contacts), array('json' => true, 'trim' => false));
            }
        } else {
            $success = $this->Accountresume->encodeData(array('success' => $success));
        }
        $this->set('success', $success);
    }

    /**
     * Admin edit
     *
     * @param int $id 
     * @return void
     * @access public
     */
    public function admin_edit($id = null) {
        $this->set('title_for_layout', __('ACCOUNT RESUME DETAIL'));

        $reportScript = $this->reportScript();
        $this->set('reportScript', $reportScript);
        
        $scriptDate = $this->datePicker();
        $this->set('scriptDate', $scriptDate);

        $redirect = array('action' => 'index');

        if (!$id && empty($this->request->data)) {
            $this->Session->setFlash(__('Invalid Contact'), 'default', array('class' => 'error'));
            $this->redirect($redirect);
        }
        if (!empty($this->request->data)) {
            $accountresume = $this->data['Accountresume'];
            $accountresume['date'] = $this->formatDate($accountresume['date']);
            $order_premium = $accountresume['order_premium']; 
            $accountresume['insurancetype_id'] = $this->data['Insurancetype']['Insurancetype'];
            $accountresume['currency_id'] = $this->data['Currency']['Currency'];

            // \edit placement detailt
            $aih_total_amount = 0;
            foreach ($this->request->data['Placementdetailt'] as $placementdetailt) {
                $aih_total_amount += $order_premium * $placementdetailt['contact_rate'] /100 * $placementdetailt['aih_rate'] /100;
            }
            $aih_total_amount = str_replace(',', '', number_format($aih_total_amount, 2));
            
            $count = 0;
            $olds = array();
            $placementdetailts = array('Placementdetailt' => array());
            $sub_order_hereon = array();
            $brokerage_rate = array();
            foreach ($this->request->data['Placementdetailt'] as $placementdetailt) {
                $sub_order_hereon[$placementdetailt['contact_id']] = $placementdetailt['contact_rate'];
                $brokerage_rate[$placementdetailt['contact_id']] = $placementdetailt['brokerage_rate'];
                if(!isset($placementdetailt['id'])) {
                    $count++;
                } else {
                    $olds[] = $placementdetailt['id'];
                }
                $placementdetailt['accountresume_id'] = $accountresume['refid'];
                $placementdetailt['refid_edit'] = $accountresume['refid_edit'];
                $temp_contact_amount = $order_premium * $placementdetailt['contact_rate'] /100 * (100 - $placementdetailt['aih_rate']) /100;
                $placementdetailt['contact_amount'] = str_replace(',', '', number_format($temp_contact_amount, 2));
                $placementdetailt['aih_total_amount'] = $aih_total_amount;
                $placementdetailt['currency_id'] = $this->data['Currency']['Currency'];
                $placementdetailt['currency'] = $accountresume['currency'];
                $placementdetailts['Placementdetailt'][] = $placementdetailt;
            }
            
            $this->Placementdetailt->saveAll($placementdetailts['Placementdetailt']);
            $lastInsertId = $this->Placementdetailt->getLastInsertId();
            $lastInsertIds = $this->Placementdetailt->find('list', array('order' => array('id desc'), 'limit' => $count, 'conditions' => array('id <=' => $lastInsertId), 'fields' => array('id')));
            $accountresume['placementdetailts'] = $this->Accountresume->encodeData(array_merge($olds, $lastInsertIds));

            // update deleted
            $placementdetail_deleteds = $this->Session->read('PlacementDetail');
            
            if ($placementdetail_deleteds != null) {
                $arr_ids = array();
                foreach ($placementdetail_deleteds as $placementdetail_deleted) {
                    $arr_ids[] = $placementdetail_deleted['Id'];
                }
                $this->Accountresume->delete_placement($arr_ids);
            }

            $count = 0;
            $olds = array();
            $paymentschedules['Paymentschedule'] = array();
            $reminders = array();
            $i = 0;
            foreach ($this->request->data['Paymentschedule'] as $paymentschedule) {
                if (!isset($paymentschedule['id'])) {
                    $count++;
                    $reminders[$i]['summary'] = $accountresume['refid_edit'] . ' - '.$paymentschedule['payer_name'].' pay to AIH';
//                    $reminders[$i]['summary'] = 'Reference #: ' . $accountresume['refid_edit'] . ' - Payment Schedule from '.$paymentschedule['payer_name'].' to '.  implode(', ', $paymentschedule['rel_market_name']);
                    $reminders[$i]['description'] = $reminders[$i]['summary'];
                    $reminders[$i]['dtstart'] = $this->formatDate($paymentschedule['broker_date']);
                    $i++;
                } else {
                    $olds[] = $paymentschedule['id'];
                    $reminder = array();
                    $reminder['summary'] = $accountresume['refid_edit'] . ' - '.$paymentschedule['payer_name'].' pay to AIH';
                    $reminder['description'] = $reminder['summary'];
                    $reminder['dtstart'] = $this->formatDate($paymentschedule['broker_date']);
                    $reminder['paymentschedule_id'] = $paymentschedule['id'];
                    $reminder['update'] = 1;
                    $this->Accountresume->reminder($reminder);
                }
                
                $markets = array();
                foreach ($paymentschedule['rel_market_id'] as $market_id) {
                    $markets[$market_id] = array(
                        $paymentschedule['rel_market_name'][$market_id],
                        $paymentschedule['rel_market_under_writer'][$market_id],
                        $paymentschedule['rel_market_date'][$market_id],
                        $paymentschedule['rel_market_amount'][$market_id],
                        $sub_order_hereon[$market_id],
                        $brokerage_rate[$market_id],);
                }
                $paymentschedule['markets'] = $this->Accountresume->encodeData($markets, array('json' => true, 'trim' => false));
                
                $paymentschedule['accountresume_id'] = $accountresume['refid'];
                $paymentschedule['refid_edit'] = $accountresume['refid_edit'];
                $paymentschedule['due_date'] = $accountresume['date'];
                $paymentschedule['broker_date'] = $this->formatDate($paymentschedule['broker_date']);
                $paymentschedule['aih_date'] = $this->formatDate($paymentschedule['aih_date']);
                $paymentschedule['currency'] = $accountresume['currency'];
                $paymentschedule['currency_id'] = $this->data['Currency']['Currency'];
                $paymentschedules['Paymentschedule'][] = $paymentschedule;
            }

            // save payment schedule
            $this->Paymentschedule->saveAll($paymentschedules['Paymentschedule']);
            $lastInsertId = $this->Paymentschedule->getLastInsertId();
            $lastInsertIds = $this->Paymentschedule->find('list', array('order' => array('id desc'), 'limit' => $count, 'conditions' => array('id <=' => $lastInsertId), 'fields' => array('id')));
            $accountresume['paymentschedules'] = $this->Accountresume->encodeData(array_merge($olds, $lastInsertIds));

            if($i>0) {
                $i--;
                foreach ($lastInsertIds as $id) {
                    $reminders[$i]['paymentschedule_id'] = $id;
                    $i--;
                }
                foreach ($reminders as $reminder) {
                    $this->Accountresume->reminder($reminder);
                }
            }
            // update deleted
            $paymentschedule_deleteds = $this->Session->read('PaymentSchedule');
            if ($paymentschedule_deleteds != null) {
                $arr_ids = array();
                foreach ($paymentschedule_deleteds as $paymentschedule_deleted) {
                    $arr_ids[] = $paymentschedule_deleted['Id'];
                }
                $this->Accountresume->delete_payment($arr_ids);
                $this->Accountresume->delete_reminder($arr_ids);
            }

            // unlock /lock
            $cur_producing_brokers = $this->Session->read('cur_producing_brokers');
            $this->Accountresume->lock($cur_producing_brokers, 'cc_aihcontacts', -1);
            $accountresume['producing_brokers'] = $this->Accountresume->encodeData($this->data['Producingbrokers']);
            $this->Accountresume->lock($this->data['Producingbrokers'], 'cc_aihcontacts', 1);
            $accountresume['markets'] = $this->Accountresume->encodeData($this->data['Markets']);
            $cur_markets = $this->Session->read('cur_markets');
            $this->Accountresume->lock($cur_markets, 'cc_markets', -1);
            $this->Accountresume->lock($this->data['Markets'], 'cc_markets', 1);
            
            $cur_insurancetype = $this->Session->read('cur_insurancetype');
            $this->Accountresume->lock($cur_insurancetype, 'cc_insurancetypes', -1);
            $this->Accountresume->lock(array($accountresume['insurancetype_id']), 'cc_insurancetypes', 1);
            $cur_currency = $this->Session->read('cur_currency');
            $this->Accountresume->lock($cur_currency, 'cc_currencies', -1);
            $this->Accountresume->lock(array($accountresume['currency_id']), 'cc_currencies', 1);

            $accountresume['from_date'] = $this->formatDate($accountresume['from_date']);
            $accountresume['to_date'] = $this->formatDate($accountresume['to_date']);

            if ($this->Accountresume->save($accountresume)) {

                //$this->Session->setFlash(__('The Account Resume has been updated'), 'default', array('class' => 'success'));

                $this->redirect($redirect);
            } else {
                $this->Session->setFlash(__('The Account Resume could not be updated. Please, try again.'), 'default', array('class' => 'error'));
            }
        }
        if (empty($this->request->data)) {
            $this->request->data = $this->Accountresume->read(null, $id);
            $cur_producing_brokers = $this->Accountresume->decodeData($this->request->data['Accountresume']['producing_brokers']);
            // unlock
            $this->Session->write('cur_producing_brokers', $cur_producing_brokers);
            $cur_data_producing_brokers = $this->Aihcontact->find('list', array('conditions' => array('Aihcontact.id' => $cur_producing_brokers, 'Aihcontact.contacttype_id' => 5)));
            $this->set('cur_data_producing_brokers', $cur_data_producing_brokers);

            $cur_markets = $this->Accountresume->decodeData($this->request->data['Accountresume']['markets']);
            // unlock
            $this->Session->write('cur_markets', $cur_markets);
            $cur_data_markets = $this->Market->find('list', array('fields' => array('Market.id', 'Market.name'), 'conditions' => array('Market.id' => $cur_markets), 'order' => array('Market.name ASC')));
            $cur_data_market_full = $this->Market->find('all', array('conditions' => array('Market.id' => $cur_markets), 'order' => array('Market.name ASC')));
            $cur_data_market_full_repair = array();
            foreach ($cur_data_market_full as $v) {
                $id = $v['Market']['id'];
                $cur_data_market_full_repair[$id] = $v;
            }
            $this->Session->write('cur_insurancetype', array($this->request->data['Accountresume']['insurancetype_id']));
            $this->Session->write('cur_currency', array($this->request->data['Accountresume']['currency_id']));
            
            $this->set('cur_data_markets', $cur_data_markets);
            $this->set('cur_data_market_full', $cur_data_market_full);
            $this->set('cur_data_market_full_repair', $cur_data_market_full_repair);
            $cur_data_aih_rate = $this->Placementdetailt->find('first', array('fields' => array('Placementdetailt.id', 'Placementdetailt.contact_rate'), 'conditions' => array('Placementdetailt.contacttype_id' => 0, 'Placementdetailt.accountresume_id' => $this->request->data['Accountresume']['refid'])));
            $cur_data_brokerage_rate = $this->Placementdetailt->find('first', array('fields' => array('Placementdetailt.id', 'Placementdetailt.contact_rate'), 'conditions' => array('Placementdetailt.contacttype_id' => 6, 'Placementdetailt.accountresume_id' => $this->request->data['Accountresume']['refid'])));
            $this->set('cur_data_aih_rate', $cur_data_aih_rate);
            $this->set('cur_data_brokerage_rate', $cur_data_brokerage_rate);

            $scriptWindowMsg = $this->windowMsg();
            $this->set('scriptWindowMsg', $scriptWindowMsg);

            $producingbrokers = $this->Aihcontact->find('list', array('conditions' => array('NOT' => array('Aihcontact.id' => $cur_producing_brokers), 'Aihcontact.contacttype_id' => 5)));
            $this->set(compact('producingbrokers'));

            $markets = $this->Market->find('list', array('fields' => array('Market.id', 'Market.name'), 'conditions' => array('NOT' => array('Market.id' => $cur_markets)), 'order' => array('Market.name ASC')));
            $this->set(compact('markets'));

            $currencies = $this->Currency->find('list', array('fields' => array('Currency.id', 'Currency.name')));
            $this->set(compact('currencies'));
            $currency = $this->Currency->find('first', array('fields' => array('Currency.id'), 'conditions' => array('Currency.name' => $this->request->data['Accountresume']['currency'])));
            $this->set(compact('currency'));

            $placementdetails = $this->Placementdetailt->find('all', array('conditions' => array('Placementdetailt.deleted' => 0, 'Placementdetailt.accountresume_id' => $this->data['Accountresume']['refid'])));
            $this->set('placementdetails', $placementdetails);

            $paymentschedules = $this->Paymentschedule->find('all', array('conditions' => array('Paymentschedule.deleted' => 0, 'Paymentschedule.accountresume_id' => $this->data['Accountresume']['refid'])));
            $this->set('paymentschedules', $paymentschedules);

            $insurancetypes = $this->Accountresume->Insurancetype->find('list');
            $this->set(compact('insurancetypes'));
        }
    }

    public function admin_debit_note($id=null) {
        $this->layout = 'admin_report_resume';
        $this->set('title_for_layout', __('DEBIT NOTE no'));

        $redirect = array('action' => 'index');

        if (!$id && empty($this->request->data)) {
            $this->Session->setFlash(__('Invalid Contact'), 'default', array('class' => 'error'));
            $this->redirect($redirect);
        }

        $this->request->data = $this->Accountresume->read(null, $id);

        $insurancetype = $this->Accountresume->Insurancetype->find('first', array('conditions' => array('Insurancetype.id' => $this->request->data['Accountresume']['insurancetype_id'])));
        $this->set('insurancetype', $insurancetype);
        
        $paymentschedules = $this->Paymentschedule->find('all', array('conditions' => array('Paymentschedule.deleted' => 0, 'Paymentschedule.accountresume_id' => $this->data['Accountresume']['refid']), 'order' => array('Paymentschedule.payer ASC'),));
        $this->set('paymentschedules', $paymentschedules);
        
        $aihcontact = $this->Aihcontact->find('first', array('conditions' => array('Aihcontact.id' => 100),));
        $this->set('aihcontact', $aihcontact);
        $bank1Ids = $this->Accountresume->decodeData($aihcontact['Aihcontact']['bank1']);
        $bank2Ids = $this->Accountresume->decodeData($aihcontact['Aihcontact']['bank2']);
        $bank1 = null;
        if(isset($bank1Ids[0])) {
            $bank1 = $this->Bank->find('first', array('conditions' => array('Bank.id' => $bank1Ids[0]),));
            $currency1 = $this->Currency->find('first', array('conditions' => array('Currency.id' => $bank1['Bank']['currency_id']),));
            $bank1['Bank']['currency_name'] = $currency1['Currency']['name'];
        }
        $bank12 = null;
        if(isset($bank1Ids[1])) {
            $bank12 = $this->Bank->find('first', array('conditions' => array('Bank.id' => $bank1Ids[1]),));
            $currency12 = $this->Currency->find('first', array('conditions' => array('Currency.id' => $bank12['Bank']['currency_id']),));
            $bank12['Bank']['currency_name'] = $currency12['Currency']['name'];
        }
        
        $bank2 = $this->Bank->find('first', array('conditions' => array('Bank.id' => $bank2Ids),));
        $this->set('aihcontact', $aihcontact);
        $this->set('bank1', $bank1);
        $this->set('bank12', $bank12);
        $this->set('bank2', $bank2);
    }

    public function admin_premium_closing($id=null, $market_id=null) {
        $this->layout = 'admin_report_resume';
        $this->set('title_for_layout', __('PREMIUM CLOSING no'));

        $redirect = array('action' => 'index');

        if (!$id && empty($this->request->data)) {
            $this->Session->setFlash(__('Invalid Contact'), 'default', array('class' => 'error'));
            $this->redirect($redirect);
        }

        $this->request->data = $this->Accountresume->read(null, $id);

        $market = $this->Market->find('first', array('conditions' => array('Market.id' => $market_id)));
        $this->set('market', $market);
        
        $insurancetype = $this->Accountresume->Insurancetype->find('first', array('conditions' => array('Insurancetype.id' => $this->request->data['Accountresume']['insurancetype_id'])));
        $this->set('insurancetype', $insurancetype);
        
        $placementdetails = $this->Placementdetailt->find('all', array('conditions' => array('Placementdetailt.deleted' => 0, 'Placementdetailt.accountresume_id' => $this->data['Accountresume']['refid'])));
        $this->set('placementdetails', $placementdetails);
        
        $paymentschedules = $this->Paymentschedule->find('all', array('conditions' => array('Paymentschedule.markets LIKE' => '%"' . $market_id . '":%', 'Paymentschedule.deleted' => 0, 'Paymentschedule.accountresume_id' => $this->data['Accountresume']['refid'])));
        $this->set('paymentschedules', $paymentschedules);
        
        $sub_order_hereon = '';
        $brokerage_rate = '';
        $total = 0;
        $premium_closings = array();
        foreach ($paymentschedules as $paymentschedule) {
            $temp = json_decode($paymentschedule['Paymentschedule']['markets'], true);
            $sub_order_hereon = $temp[$market_id][4];
            $brokerage_rate = $temp[$market_id][5];
            $total += $temp[$market_id][3];
            $premium_closings[] = $temp[$market_id];
            
        }
        $this->set('sub_order_hereon', $sub_order_hereon);
        $this->set('brokerage_rate', $brokerage_rate);
        $this->set('total', $total);
        $this->set('premium_closings', $premium_closings);
    }

    public function admin_cover_note($id=null) {
        $this->layout = 'admin_report';
        $this->set('title_for_layout', __('COVER NOTE no'));

        $redirect = array('action' => 'index');

        if (!$id && empty($this->request->data)) {
            $this->Session->setFlash(__('Invalid Contact'), 'default', array('class' => 'error'));
            $this->redirect($redirect);
        }

        $this->request->data = $this->Accountresume->read(null, $id);

        $cur_reinsured = $this->Accountresume->decodeData($this->request->data['Accountresume']['reinsured']);
        $cur_data_reinsured = $this->Aihcontact->find('list', array('conditions' => array('Aihcontact.id' => $cur_reinsured, 'Aihcontact.contacttype_id' => 1)));
        $this->set('cur_data_reinsured', $cur_data_reinsured);

        $cur_original_insured = $this->Accountresume->decodeData($this->request->data['Accountresume']['original_insured']);
        $cur_data_original_insured = $this->Aihcontact->find('list', array('conditions' => array('Aihcontact.id' => $cur_original_insured, 'Aihcontact.contacttype_id' => 3)));
        $this->set('cur_data_original_insured', $cur_data_original_insured);

        $insurancetype = $this->Accountresume->Insurancetype->find('first', array('conditions' => array('Insurancetype.id' => $this->request->data['Accountresume']['insurancetype_id'])));
        $this->set('insurancetype', $insurancetype);
        
        $paymentschedules = $this->Paymentschedule->find('all', array('conditions' => array('Paymentschedule.deleted' => 0, 'Paymentschedule.accountresume_id' => $this->data['Accountresume']['refid'])));
        $this->set('paymentschedules', $paymentschedules);
    }
    
    public function admin_upload_cover_note($id=null) {
        $this->layout = 'admin_report';
        $this->set('title_for_layout', __('COVER NOTE no'));

        $script = '';
        $redirect = array('action' => 'index');

        if (!$id && empty($this->request->data)) {
            $this->Session->setFlash(__('Invalid Contact'), 'default', array('class' => 'error'));
            $this->redirect($redirect);
        }

        if (!empty($this->request->data)) {
            if($this->request->data['Accountresume']['file']['name'] != '') {
                $old_file = '';
                if(isset($this->request->data['Accountresume']['attached'])) {
                    $old_file = $this->request->data['Accountresume']['attached'];
                }
                $file = $this->request->data['Accountresume']['file'];
                unset($this->request->data['Accountresume']['file']);

                if($file['type'] == 'application/pdf'
                        || $file['type'] == 'application/msword' 
                        || $file['type'] == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' 
                        || $file['type'] == 'application/excel' 
                        || $file['type'] == 'application/vnd.ms-excel' 
                        || $file['type'] == 'application/x-excel' 
                        || $file['type'] == 'application/x-msexcel' 
                        || $file['type'] == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
                        || $file['type'] == 'text/plain') {
                    $poidsMax = ini_get('post_max_size');
                    if((intval($poidsMax)*1024*1024) > $file['size']){
                        // check if file with same path exists
                        $destination = WWW_ROOT . 'uploads' . DS . $file['name'];
                        $old_destination = WWW_ROOT . $this->uploadsDir . DS . $old_file;
                        if (file_exists($destination)) {
                            $newFileName = uniqid() . '-' . $file['name'];
                            $destination = WWW_ROOT . 'uploads' . DS . $newFileName;
                        } else {
                            $newFileName = $file['name'];
                        }
                        //php_debug($destination);

                        $this->request->data['Accountresume']['attached'] = $newFileName;
                        $this->request->data['Accountresume']['mime_type'] = $file['type'];
                        $this->request->data['Accountresume']['path'] = '/uploads/' . $newFileName;

                        if ($this->Accountresume->save($this->request->data)) {
                            // move the file
                            move_uploaded_file($file['tmp_name'], $destination);
                            if(file_exists($old_destination)) {
                                unlink($old_destination);
                            }
    //                        $this->Session->setFlash(__('The Broking Inquiry has been saved'), 'default', array('class' => 'success'));
                            //$script = "var t=setTimeout('self.close()', 1000);";
    //                        $this->redirect($redirect);
                        } else {
                            $this->Session->setFlash(__('The COVER NOTE could not be saved. Please, try again.'), 'default', array('class' => 'error'));
                        } 
                    } else {
                        $this->Session->setFlash(__('Can not upload file over ' + $poidsMax), 'default', array('class' => 'error'));
                    }
                } else {
                    $this->Session->setFlash(__('Attachment allow the following formats *.pdf *.doc, *.docx, *.xls, *.xlsx, *.txt. Please, try again.'), 'default', array('class' => 'error'));
                }
            } else {
                $this->Session->setFlash(__('No file uploaded, try again.'), 'default', array('class' => 'error'));
            }
        } 
        
        $this->request->data = $this->Accountresume->read(null, $id);
        $this->set('script', $script);
    }

    /**
     * Admin delete
     *
     * @param int $id 
     * @return void
     * @access public
     */
    public function admin_delete($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid id for Account Resume'), 'default', array('class' => 'error'));
            $this->redirect(array('action' => 'index'));
        }

        $accountresume = $this->Accountresume->find('first', array(
                    'conditions' => array(
                        'Accountresume.id' => $id,
                    ),
                ));
        if (isset($accountresume['Accountresume'])) {
            // unlock
            $cur_producing_brokers = json_decode($accountresume['Accountresume']['producing_brokers'], true);
            $this->Accountresume->lock($cur_producing_brokers, 'cc_aihcontacts', -1);
            $cur_markets = json_decode($accountresume['Accountresume']['markets'], true);
            $this->Accountresume->lock($cur_markets, 'cc_markets', -1);
            $this->Accountresume->lock(array($accountresume['Accountresume']['insurancetype_id']), 'cc_insurancetypes', -1);
            $this->Accountresume->lock(array($accountresume['Accountresume']['currency_id']), 'cc_currencies', -1);
//            $placementdetail = $this->Placementdetailt->find('first', array('condictions' => array('Placementdetailt.accountresume_id' => $accountresume['Accountresume']['refid'])));
//            if($placementdetail != null) {
//                $this->Session->setFlash(__('Can\'t delete Account Resume, because it has Placement detail'), 'default', array('class' => 'success'));
//                $this->redirect(array('action' => 'index'));
//            }
//            $paymentschedule = $this->Paymentschedule->find('first', array('condictions' => array('Paymentschedule.accountresume_id' => $accountresume['Accountresume']['refid'])));
//            if($paymentschedule != null) {
//                $this->Session->setFlash(__('Can\'t delete Account Resume, because it has Payment schedule'), 'default', array('class' => 'success'));
//                $this->redirect(array('action' => 'index'));
//            }
            if ($this->Accountresume->delete($id)) {
                $this->Accountresume->delete_payment(null, $accountresume['Accountresume']['refid']);
                $this->Accountresume->delete_reminder(json_decode($accountresume['Accountresume']['paymentschedules']));
                $this->Accountresume->delete_placement(null, $accountresume['Accountresume']['refid']);
                
//                $this->Session->setFlash(__('Account Resume deleted'), 'default', array('class' => 'success'));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->redirect(array('action' => 'index'));
            }
        } else {
//            $this->Session->setFlash(__('Invalid id for Account Resume'), 'default', array('class' => 'error'));
            $this->redirect(array('action' => 'index'));
        }
    }

    public function datePicker() {
        $output = "$(function() {
                        $('#AccountresumeDate').datepicker({ changeYear: true, dateFormat: 'm/d/yy'});
                        $('#AccountresumeFromDate').datepicker({ changeYear: true, dateFormat: 'm/d/yy'});
                        $('#AccountresumeToDate').datepicker({ changeYear: true, dateFormat: 'm/d/yy'});
                        $('input.jdate').datepicker({ changeYear: true, dateFormat: 'm/d/yy'});
                        return false;
                    });";
        return $output;
    }

    public function formatDate($str) {
        $temp = explode('/', $str);
        return $temp[2] . '-' . $temp[0] . '-' . $temp[1];
    }

    public function scriptSearchBox() {
        $output = "
            $(function() {
                $('#search_button').click(function(){
                    if($('#search_text').val() == ''){
                        alert('Search box is empty. Please type a keyword to search!');
                    }else{
                        $(location).attr('href','" . Router::url('/admin/accountresumes/search/q:', true) . "' + $('#search_text').val());
                        $(document).SearchHighlight({exact:'whole'});    
                    }
                });
                $('#search_text').keypress(function(event) {
                    if ( event.which == 13 ) {
                        event.preventDefault();
                        $(location).attr('href','" . Router::url('/admin/accountresumes/search/q:', true) . "' + $('#search_text').val());
                        $(document).SearchHighlight({exact:'whole'});
                    }
                });
            });";
        return $output;
    }
    public function admin_pdf_review($id = null) {
        $this->layout = 'admin_report_resume';
        $this->set('title_for_layout', __('ACCOUNT RESUME DETAIL'));

        $reportScript = $this->reportScript();
        $this->set('reportScript', $reportScript);
        
        $scriptDate = $this->datePicker();
        $this->set('scriptDate', $scriptDate);

        $redirect = array('action' => 'index');

        if (!$id && empty($this->request->data)) {
            $this->Session->setFlash(__('Invalid Contact'), 'default', array('class' => 'error'));
            $this->redirect($redirect);
        }

        if (empty($this->request->data)) {
            $this->request->data = $this->Accountresume->read(null, $id);
            $cur_producing_brokers = $this->Accountresume->decodeData($this->request->data['Accountresume']['producing_brokers']);
            // unlock
            $this->Session->write('cur_producing_brokers', $cur_producing_brokers);
            $cur_data_producing_brokers = $this->Aihcontact->find('list', array('conditions' => array('Aihcontact.id' => $cur_producing_brokers, 'Aihcontact.contacttype_id' => 5)));
            $this->set('cur_data_producing_brokers', $cur_data_producing_brokers);

            $cur_markets = $this->Accountresume->decodeData($this->request->data['Accountresume']['markets']);
            // unlock
            $this->Session->write('cur_markets', $cur_markets);
            $cur_data_markets = $this->Market->find('list', array('fields' => array('Market.id', 'Market.name'), 'conditions' => array('Market.id' => $cur_markets), 'order' => array('Market.name ASC')));
            $cur_data_market_full = $this->Market->find('all', array('conditions' => array('Market.id' => $cur_markets), 'order' => array('Market.name ASC')));
            $cur_data_market_full_repair = array();
            foreach ($cur_data_market_full as $v) {
                $id = $v['Market']['id'];
                $cur_data_market_full_repair[$id] = $v;
            }
            $this->Session->write('cur_insurancetype', array($this->request->data['Accountresume']['insurancetype_id']));
            $this->Session->write('cur_currency', array($this->request->data['Accountresume']['currency_id']));
            
            $this->set('cur_data_markets', $cur_data_markets);
            $this->set('cur_data_market_full', $cur_data_market_full);
            $this->set('cur_data_market_full_repair', $cur_data_market_full_repair);
            $cur_data_aih_rate = $this->Placementdetailt->find('first', array('fields' => array('Placementdetailt.id', 'Placementdetailt.contact_rate'), 'conditions' => array('Placementdetailt.contacttype_id' => 0, 'Placementdetailt.accountresume_id' => $this->request->data['Accountresume']['refid'])));
            $cur_data_brokerage_rate = $this->Placementdetailt->find('first', array('fields' => array('Placementdetailt.id', 'Placementdetailt.contact_rate'), 'conditions' => array('Placementdetailt.contacttype_id' => 6, 'Placementdetailt.accountresume_id' => $this->request->data['Accountresume']['refid'])));
            $this->set('cur_data_aih_rate', $cur_data_aih_rate);
            $this->set('cur_data_brokerage_rate', $cur_data_brokerage_rate);

            $scriptWindowMsg = $this->windowMsg();
            $this->set('scriptWindowMsg', $scriptWindowMsg);

            $placementdetails = $this->Placementdetailt->find('all', array('conditions' => array('Placementdetailt.deleted' => 0, 'Placementdetailt.accountresume_id' => $this->data['Accountresume']['refid'])));
            $this->set('placementdetails', $placementdetails);

            $paymentschedules = $this->Paymentschedule->find('all', array('conditions' => array('Paymentschedule.deleted' => 0, 'Paymentschedule.accountresume_id' => $this->data['Accountresume']['refid'])));
            $this->set('paymentschedules', $paymentschedules);

            $cur_insurancetypes = $this->Insurancetype->find('first',array('conditions' => array('Insurancetype.id' => $this->data['Accountresume']['insurancetype_id'],)));
            $this->set('insurancetypes', $cur_insurancetypes['Insurancetype']['name']);
        }
    }

}

?>